// node createGeojson.js

import fs from 'fs';

const getAreaList = async ({ name, id: p_id }) => {
    let res = await fetch("https://api-admin.petslib.cn/erp/v1/area/list", {
        "headers": {
            "app-id": "11",
            "corporation-id": "607C4FD9-2554-11EB-9E85-00163E0DCF22",
            "authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImp0aSI6ImRiMmQwODRhMzNhMiJ9.eyJpc3MiOiJodHRwOi8vZXJwZnJvbnQuZm1wZXRzLmNuIiwiYXVkIjoiaHR0cDovL2VycGZyb250LmZtcGV0cy5jbiIsImp0aSI6ImRiMmQwODRhMzNhMiIsImlhdCI6MTcxNTI0MDEyNywiZXhwIjoxNzE1MzI2NTI3LCJ1aWQiOiI0NDNCM0Y1MS0xNTRELTExRUMtQjExQy05ODAzOUI4ODdGMUEiLCJsb2dpbl9uYW1lIjoi5L2V5bmzIiwiZW52IjoicHJvZCJ9._yGap4ghyiNycnnU47pfjYPkr5AMUvs_VrhhAy4pJ3c",
        },
        "body": JSON.stringify({ "p_id": p_id, "page": 1, "limit": 1000, "start": 0 }),
        "method": "POST"
    });
    res = await res.json();
    res = res.data.list;
    console.log(`[getAreaList] ${name} ${p_id}: `, res.length);
    return res;
}

// https://datav.aliyun.com/portal/school/atlas/area_selector
// https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=100000_full
const fetchGeojson = async (adcode) => {
    let retryCount = 0
    const fn = async (adcode, retry = false) => {
        const code = retry ? adcode : `${adcode}_full`
        let res = await fetch(`https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=${code}`);
        res = await res.text();
        console.log('[fetchGeojson] ' + adcode + ' res.length', res.length);
        if (res.startsWith('{')) {
            return res;
        }
        if (retryCount < 1) {
            retryCount++
            return await fn(adcode, true)
        }
        throw '失败'
    }
    return await fn(adcode)
}

const getFilePath = (filename) => {
    return `${process.cwd()}/geojson/${filename}_full.json`;
};

const writeFile = (filename, text) => new Promise((resolve, reject) => {
    fs.writeFile(getFilePath(filename), text, 'utf8', (err) => {
        if (err) {
            return reject(err);
        }
        resolve()
    });
});

// https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json
// https://geo.datav.aliyun.com/areas_v3/bound/710000_full.json
// https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=710000

const failedList = []

const loadGeojson = async (list, province, city) => {
    for (const { adcode, name } of list) {
        if (fs.existsSync(getFilePath(adcode))) {
            const rc = fs.readFileSync(getFilePath(adcode), 'utf8');
            if (rc.startsWith('{')) {
                console.log(`[loadGeojson existed] ${name} ${adcode}`);
                continue;
            }
        }
        try {
            const text = await fetchGeojson(adcode);
            console.log(`[loadGeojson success] ${name} ${adcode}`);
            await writeFile(adcode, text);
        } catch (error) {
            failedList.push(`${province?.name || ''}/${city?.name || ''}/${name}:${adcode}`)
            console.log(`[loadGeojson failed] ${name} ${adcode}`);
        }
    }
}

const quanguo = { adcode: 100000, id: 1, name: '全国' }

loadGeojson([quanguo])
// 省级
getAreaList(quanguo).then(async (provinceList) => {
    await loadGeojson(provinceList)
    // 市级
    for (const province of provinceList) {
        const cityList = await getAreaList(province)
        await loadGeojson(cityList, province)
        // 区级
        for (const city of cityList) {
            const areaList = await getAreaList(city)
            await loadGeojson(areaList, province, city)
        }
    }

    console.log(failedList)
    console.log('失败数量', failedList.length)
})
